package com.ll.gulimall.ware.listener;

import com.ll.common.to.mq.OrderTo;
import com.ll.common.to.ware.WareLockTo;


import com.ll.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 释放库存监听器
 */
@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class WareLockListener {

    @Autowired
    WareSkuService wareSkuService;


    /**
     * 释放库存
     * 在此期间发生异常则是解锁失败 无异常则是解锁成功
     *
     * @param message 消息
     * @param lockTo  发送的数据
     * @param channel 通道
     */
    @RabbitHandler
    public void releaseWare(Message message, WareLockTo lockTo, Channel channel) throws IOException {
        try {
            //确认收到消息处理完毕
            wareSkuService.releaseWare(message, lockTo, channel);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //重新放入队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        }


    }


    /**
     * 订单关闭 直接释放库存的消息
     * @param message
     * @param order
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void orderCloseReleaseWare(Message message, OrderTo order, Channel channel) throws IOException {
        try {
            //确认收到消息处理完毕
            wareSkuService.releaseWare(message, order, channel);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //重新放入队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }


    }
}
